{% extends "base.html" %}

{% block title %}取消预约{% endblock %}

{% block extra_css %}
<style>
    .cancel-header {
        background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);
        color: white;
        padding: 2rem 0;
        border-radius: 0 0 1rem 1rem;
        margin-bottom: 2rem;
    }

    .cancel-card {
        background: white;
        border-radius: 1rem;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
        overflow: hidden;
        margin-bottom: 2rem;
    }

    .warning-section {
        background: linear-gradient(135deg, #fff3cd, #ffeaa7);
        border-left: 4px solid #ffc107;
        padding: 1.5rem;
        margin-bottom: 1.5rem;
    }

    .warning-title {
        color: #856404;
        font-weight: bold;
        margin-bottom: 1rem;
    }

    .warning-list {
        color: #856404;
        margin-bottom: 0;
    }

    .reservation-summary {
        background: #f8f9fa;
        border-radius: 0.75rem;
        padding: 1.5rem;
        margin-bottom: 1.5rem;
    }

    .summary-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0.75rem 0;
        border-bottom: 1px solid #e9ecef;
    }

    .summary-item:last-child {
        border-bottom: none;
        font-weight: bold;
        font-size: 1.1rem;
    }

    .summary-label {
        color: #6c757d;
    }

    .summary-value {
        color: #2c3e50;
        font-weight: 500;
    }

    .fee-calculation {
        background: linear-gradient(135deg, #f8d7da, #f5c2c7);
        border-left: 4px solid #dc3545;
        border-radius: 0 0.75rem 0.75rem 0;
        padding: 1.5rem;
        margin-bottom: 1.5rem;
    }

    .fee-title {
        color: #721c24;
        font-weight: bold;
        margin-bottom: 1rem;
    }

    .fee-breakdown {
        margin-bottom: 1rem;
    }

    .fee-item {
        display: flex;
        justify-content: space-between;
        padding: 0.5rem 0;
        color: #721c24;
    }

    .fee-total {
        border-top: 2px solid #dc3545;
        padding-top: 0.75rem;
        font-weight: bold;
        font-size: 1.1rem;
    }

    .policy-section {
        background: #e2e3e5;
        border-radius: 0.75rem;
        padding: 1.5rem;
        margin-bottom: 1.5rem;
    }

    .policy-title {
        color: #495057;
        font-weight: bold;
        margin-bottom: 1rem;
    }

    .policy-list {
        color: #6c757d;
        margin-bottom: 0;
    }

    .cancel-form {
        background: white;
        padding: 1.5rem;
        border-radius: 0.75rem;
        border: 1px solid #e9ecef;
    }

    .form-section {
        margin-bottom: 2rem;
    }

    .form-section:last-child {
        margin-bottom: 0;
    }

    .section-title {
        color: #2c3e50;
        font-weight: bold;
        margin-bottom: 1rem;
        padding-bottom: 0.5rem;
        border-bottom: 1px solid #e9ecef;
    }

    .reason-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 1rem;
        margin-bottom: 1rem;
    }

    .reason-option {
        background: #f8f9fa;
        border: 2px solid #e9ecef;
        border-radius: 0.5rem;
        padding: 1rem;
        text-align: center;
        cursor: pointer;
        transition: all 0.3s ease;
    }

    .reason-option:hover {
        border-color: #6c757d;
        background: #e9ecef;
    }

    .reason-option.selected {
        border-color: #dc3545;
        background: #f8d7da;
        color: #721c24;
    }

    .reason-option input[type="radio"] {
        display: none;
    }

    .reason-icon {
        font-size: 2rem;
        margin-bottom: 0.5rem;
        display: block;
    }

    .countdown-warning {
        background: linear-gradient(135deg, #ff6b6b, #ff8e53);
        color: white;
        padding: 1rem;
        border-radius: 0.5rem;
        text-align: center;
        margin-bottom: 1.5rem;
    }

    .countdown-time {
        font-size: 1.5rem;
        font-weight: bold;
        margin-bottom: 0.5rem;
    }

    .countdown-label {
        font-size: 0.875rem;
        opacity: 0.9;
    }

    .cancel-actions {
        background: #f8f9fa;
        padding: 1.5rem;
        border-top: 1px solid #e9ecef;
        text-align: center;
    }

    .refund-info {
        background: linear-gradient(135deg, #d1ecf1, #bee5eb);
        border-left: 4px solid #17a2b8;
        border-radius: 0 0.75rem 0.75rem 0;
        padding: 1.5rem;
        margin-bottom: 1.5rem;
    }

    .refund-title {
        color: #0c5460;
        font-weight: bold;
        margin-bottom: 1rem;
    }

    .refund-amount {
        font-size: 1.5rem;
        font-weight: bold;
        color: #17a2b8;
        text-align: center;
    }

    @media (max-width: 768px) {
        .cancel-header {
            padding: 1rem 0;
        }

        .reason-grid {
            grid-template-columns: 1fr;
        }

        .summary-item,
        .fee-item {
            flex-direction: column;
            align-items: flex-start;
        }

        .summary-value {
            margin-top: 0.25rem;
        }

        .countdown-time {
            font-size: 1.25rem;
        }
    }
</style>
{% endblock %}

{% block content %}
<div class="cancel-header">
    <div class="container">
        <div class="row align-items-center">
            <div class="col-md-8">
                <h1 class="mb-0">
                    <i class="fas fa-ban me-2"></i>取消预约
                </h1>
                <p class="mb-0 mt-2 opacity-75">预约编号：#{{ reservation.id }}</p>
            </div>
            <div class="col-md-4 text-end">
                <a href="{{ url_for('coach_reservations.detail', id=reservation.id) }}" class="btn btn-light">
                    <i class="fas fa-arrow-left me-1"></i>返回详情
                </a>
            </div>
        </div>
    </div>
</div>

<div class="container">
    <div class="row">
        <div class="col-lg-8">
            <!-- 警告提示 -->
            <div class="warning-section">
                <div class="warning-title">
                    <i class="fas fa-exclamation-triangle me-2"></i>取消预约注意事项
                </div>
                <ul class="warning-list">
                    <li>取消预约后将无法恢复，请谨慎操作</li>
                    <li>根据取消时间不同，可能产生不同的取消费用</li>
                    <li>频繁取消可能影响您的信誉评级</li>
                    <li>学员将收到取消通知，建议提前沟通</li>
                </ul>
            </div>

            <!-- 距离课程开始时间倒计时 -->
            {% if reservation.is_upcoming %}
            <div class="countdown-warning" id="countdownWarning">
                <div class="countdown-time" id="countdownTime">
                    {{ reservation.time_until_start }}
                </div>
                <div class="countdown-label">距离课程开始</div>
            </div>
            {% endif %}

            <!-- 预约摘要 -->
            <div class="cancel-card">
                <div class="card-header bg-light">
                    <h5 class="mb-0">预约信息确认</h5>
                </div>
                <div class="card-body">
                    <div class="reservation-summary">
                        <div class="summary-item">
                            <span class="summary-label">学员姓名</span>
                            <span class="summary-value">{{ reservation.student.name }}</span>
                        </div>
                        <div class="summary-item">
                            <span class="summary-label">预约日期</span>
                            <span class="summary-value">{{ reservation.reservation_date.strftime('%Y年%m月%d日 %A') }}</span>
                        </div>
                        <div class="summary-item">
                            <span class="summary-label">上课时间</span>
                            <span class="summary-value">
                                {{ reservation.start_time.strftime('%H:%M') }} - {{ reservation.end_time.strftime('%H:%M') }}
                                <small class="text-muted">({{ reservation.duration_minutes }}分钟)</small>
                            </span>
                        </div>
                        <div class="summary-item">
                            <span class="summary-label">球台</span>
                            <span class="summary-value">{{ reservation.table.name }}</span>
                        </div>
                        <div class="summary-item">
                            <span class="summary-label">课程费用</span>
                            <span class="summary-value text-primary">¥{{ reservation.price or 0 }}</span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 取消原因表单 -->
            <div class="cancel-card">
                <div class="card-header bg-light">
                    <h5 class="mb-0">取消原因</h5>
                </div>
                <div class="card-body">
                    <form id="cancelForm">
                        <div class="form-section">
                            <div class="section-title">请选择取消原因</div>
                            <div class="reason-grid">
                                <label class="reason-option">
                                    <input type="radio" name="cancel_reason" value="schedule_conflict">
                                    <i class="fas fa-calendar-times reason-icon"></i>
                                    <div>时间冲突</div>
                                    <small class="text-muted">其他重要安排</small>
                                </label>

                                <label class="reason-option">
                                    <input type="radio" name="cancel_reason" value="student_request">
                                    <i class="fas fa-user-times reason-icon"></i>
                                    <div>学员取消</div>
                                    <small class="text-muted">学员主动取消</small>
                                </label>

                                <label class="reason-option">
                                    <input type="radio" name="cancel_reason" value="illness">
                                    <i class="fas fa-user-injured reason-icon"></i>
                                    <div>身体不适</div>
                                    <small class="text-muted">健康原因无法授课</small>
                                </label>

                                <label class="reason-option">
                                    <input type="radio" name="cancel_reason" value="emergency">
                                    <i class="fas fa-exclamation-circle reason-icon"></i>
                                    <div>紧急情况</div>
                                    <small class="text-muted">突发紧急事件</small>
                                </label>

                                <label class="reason-option">
                                    <input type="radio" name="cancel_reason" value="weather">
                                    <i class="fas fa-cloud-rain reason-icon"></i>
                                    <div>天气原因</div>
                                    <small class="text-muted">恶劣天气影响</small>
                                </label>

                                <label class="reason-option">
                                    <input type="radio" name="cancel_reason" value="other">
                                    <i class="fas fa-ellipsis-h reason-icon"></i>
                                    <div>其他原因</div>
                                    <small class="text-muted">详细说明</small>
                                </label>
                            </div>
                        </div>

                        <div class="form-section">
                            <div class="section-title">详细说明</div>
                            <textarea class="form-control" name="cancel_notes" rows="4"
                                      placeholder="请详细说明取消原因，这将有助于我们改进服务质量..."></textarea>
                            <div class="form-text">此信息将发送给学员，请保持专业和礼貌的语调</div>
                        </div>

                        <div class="form-section">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="notifyStudent" name="notify_student" checked>
                                <label class="form-check-label" for="notifyStudent">
                                    发送取消通知给学员
                                </label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="suggestReschedule" name="suggest_reschedule">
                                <label class="form-check-label" for="suggestReschedule">
                                    建议重新安排课程时间
                                </label>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <div class="col-lg-4">
            <!-- 费用计算 -->
            {% if reservation.price %}
            <div class="fee-calculation">
                <div class="fee-title">
                    <i class="fas fa-calculator me-2"></i>取消费用计算
                </div>
                <div class="fee-breakdown">
                    <div class="fee-item">
                        <span>课程原价</span>
                        <span>¥{{ reservation.price }}</span>
                    </div>
                    <div class="fee-item">
                        <span>取消手续费</span>
                        <span id="cancelFee">¥{{ cancel_fee }}</span>
                    </div>
                    <div class="fee-item fee-total">
                        <span>应退金额</span>
                        <span id="refundAmount">¥{{ refund_amount }}</span>
                    </div>
                </div>
                <div class="text-center mt-2">
                    <small class="text-muted">具体费用以最终结算为准</small>
                </div>
            </div>
            {% endif %}

            <!-- 退款信息 -->
            {% if refund_amount > 0 %}
            <div class="refund-info">
                <div class="refund-title">
                    <i class="fas fa-money-bill-wave me-2"></i>退款说明
                </div>
                <div class="refund-amount">¥{{ refund_amount }}</div>
                <p class="mb-0 mt-2 text-center">
                    <small>退款将在3-5个工作日内原路返回</small>
                </p>
            </div>
            {% endif %}

            <!-- 取消政策 -->
            <div class="policy-section">
                <div class="policy-title">
                    <i class="fas fa-file-contract me-2"></i>取消政策
                </div>
                <ul class="policy-list">
                    <li>课程开始前24小时：免费取消</li>
                    <li>课程开始前2-24小时：收取50%费用</li>
                    <li>课程开始前2小时内：收取全额费用</li>
                    <li>每月取消次数超过3次将收取额外费用</li>
                </ul>
            </div>

            <!-- 操作按钮 -->
            <div class="cancel-actions">
                <div class="d-grid gap-2">
                    <button type="button" class="btn btn-danger btn-lg" onclick="submitCancel()" id="cancelBtn">
                        <i class="fas fa-ban me-2"></i>确认取消预约
                    </button>
                    <a href="{{ url_for('coach_reservations.detail', id=reservation.id) }}" class="btn btn-outline-secondary">
                        <i class="fas fa-arrow-left me-2"></i>暂不取消
                    </a>
                </div>

                <div class="mt-3">
                    <small class="text-muted">
                        <i class="fas fa-info-circle me-1"></i>
                        如需帮助，请联系客服：400-123-4567
                    </small>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 确认取消模态框 -->
<div class="modal fade" id="confirmCancelModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title">
                    <i class="fas fa-exclamation-triangle me-2"></i>确认取消预约
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-warning">
                    <h6><i class="fas fa-exclamation-triangle me-2"></i>请仔细确认</h6>
                    <ul class="mb-0">
                        <li>此操作无法撤销</li>
                        <li>学员将收到取消通知</li>
                        <li>可能产生取消费用</li>
                        <li>影响您的教练信誉</li>
                    </ul>
                </div>

                <div class="cancel-summary">
                    <h6>取消信息汇总：</h6>
                    <div class="table-responsive">
                        <table class="table table-sm">
                            <tr>
                                <td>学员</td>
                                <td>{{ reservation.student.name }}</td>
                            </tr>
                            <tr>
                                <td>时间</td>
                                <td>{{ reservation.reservation_date.strftime('%m/%d') }} {{ reservation.start_time.strftime('%H:%M') }}</td>
                            </tr>
                            <tr>
                                <td>取消原因</td>
                                <td id="summaryReason">-</td>
                            </tr>
                            {% if reservation.price %}
                            <tr>
                                <td>退款金额</td>
                                <td class="text-success">¥<span id="summaryRefund">{{ refund_amount }}</span></td>
                            </tr>
                            {% endif %}
                        </table>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">再考虑一下</button>
                <button type="button" class="btn btn-danger" onclick="confirmCancel()" id="finalCancelBtn">
                    <i class="fas fa-ban me-2"></i>确认取消
                </button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
$(document).ready(function() {
    // 原因选择
    $('.reason-option').click(function() {
        $('.reason-option').removeClass('selected');
        $(this).addClass('selected');
        $(this).find('input[type="radio"]').prop('checked', true);

        updateCancelButton();
    });

    // 监听表单变化
    $('#cancelForm input, #cancelForm textarea').on('change input', function() {
        updateCancelButton();
    });

    // 倒计时更新
    {% if reservation.is_upcoming %}
    updateCountdown();
    setInterval(updateCountdown, 1000);
    {% endif %}
});

// 更新倒计时
function updateCountdown() {
    const now = new Date();
    const startTime = new Date('{{ reservation.reservation_date.strftime("%Y-%m-%d") }} {{ reservation.start_time.strftime("%H:%M") }}');
    const diff = startTime - now;

    if (diff <= 0) {
        $('#countdownWarning').html(`
            <div class="countdown-time">课程已开始</div>
            <div class="countdown-label">取消将收取全额费用</div>
        `);
        return;
    }

    const hours = Math.floor(diff / (1000 * 60 * 60));
    const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));

    let timeText = '';
    if (hours > 0) {
        timeText = `${hours}小时${minutes}分钟`;
    } else {
        timeText = `${minutes}分钟`;
    }

    $('#countdownTime').text(timeText);

    // 更新费用计算
    updateFeeCalculation(hours);
}

// 更新费用计算
function updateFeeCalculation(hoursUntilStart) {
    const originalPrice = {{ reservation.price or 0 }};
    let cancelFee = 0;
    let refundAmount = originalPrice;

    if (hoursUntilStart < 2) {
        // 2小时内：全额费用
        cancelFee = originalPrice;
        refundAmount = 0;
    } else if (hoursUntilStart < 24) {
        // 2-24小时：50%费用
        cancelFee = originalPrice * 0.5;
        refundAmount = originalPrice * 0.5;
    }

    $('#cancelFee').text('¥' + cancelFee.toFixed(0));
    $('#refundAmount').text('¥' + refundAmount.toFixed(0));
    $('#summaryRefund').text(refundAmount.toFixed(0));
}

// 更新取消按钮状态
function updateCancelButton() {
    const reasonSelected = $('input[name="cancel_reason"]:checked').length > 0;
    $('#cancelBtn').prop('disabled', !reasonSelected);
}

// 提交取消
function submitCancel() {
    const formData = $('#cancelForm').serialize();
    const selectedReason = $('input[name="cancel_reason"]:checked');

    if (selectedReason.length === 0) {
        showAlert('error', '请选择取消原因');
        return;
    }

    // 更新确认框中的信息
    const reasonText = selectedReason.closest('.reason-option').find('div').first().text();
    $('#summaryReason').text(reasonText);

    $('#confirmCancelModal').modal('show');
}

// 确认取消
function confirmCancel() {
    $('#finalCancelBtn').prop('disabled', true).html('<i class="fas fa-spinner fa-spin me-2"></i>处理中...');

    const formData = {
        cancel_reason: $('input[name="cancel_reason"]:checked').val(),
        cancel_notes: $('textarea[name="cancel_notes"]').val(),
        notify_student: $('#notifyStudent').is(':checked'),
        suggest_reschedule: $('#suggestReschedule').is(':checked')
    };

    $.post('{{ url_for("coach_reservations.api_cancel_reservation", reservation_id=reservation.id) }}', formData, function(response) {
        if (response.success) {
            showAlert('success', '预约已成功取消');
            $('#confirmCancelModal').modal('hide');
            setTimeout(() => {
                window.location.href = '{{ url_for("coach_reservations.confirmed") }}';
            }, 2000);
        } else {
            showAlert('error', response.message || '取消预约失败');
            $('#finalCancelBtn').prop('disabled', false).html('<i class="fas fa-ban me-2"></i>确认取消');
        }
    }).fail(function() {
        showAlert('error', '网络错误，请重试');
        $('#finalCancelBtn').prop('disabled', false).html('<i class="fas fa-ban me-2"></i>确认取消');
    });
}

// 显示提示信息
function showAlert(type, message) {
    const alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
    const icon = type === 'success' ? 'check-circle' : 'exclamation-triangle';

    const alert = $(`
        <div class="alert ${alertClass} alert-dismissible fade show position-fixed"
             style="top: 20px; right: 20px; z-index: 9999;">
            <i class="fas fa-${icon} me-2"></i>${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    `);

    $('body').append(alert);

    setTimeout(function() {
        alert.alert('close');
    }, 5000);
}
</script>
{% endblock %}